var USERS;

$(document).ready(function() {
    // -------------------------------------------------------------------
    // Midgard functions
    // -------------------------------------------------------------------
    var quarterArray = [
        {0:"Januar",  1:"Februar",   2:"Mars"},
        {3:"April",   4:"Mai",       5:"Juni"},
        {6:"Juli",    7:"August",    8:"September"},
        {9:"Oktober", 10:"November", 11:"Desember"}
    ];
    
    var getCreator = function() {
        return {
            name: $('#homeBtn').data("name"),
            id:   $('#homeBtn').data("userid")
        }
    };
    
    var months = ["Januar","Februar","Mars","April",
                  "Mai","Juni","Juli","August",
                  "September","Oktober","November","Desember"]

    // #content: refreshes contents so stuff is up to date =)))))
    var refreshContent = function() {
        // var currentView = $('#content').data("currentView");
        _.delay(function() {
            console.log("Refreshing #content");
            $('nav li a.selected').click();
        }, 400);
    };
    
    $('.ribbonhint').tooltip({placement: 'right'});

    $('#homeBtn').dropdown();
    $('#createBtn').dropdown();

    now.remoteIdeaPositionUpdate = function(id,x,y) {
        $('.idea').each(function(ideaElement) {
            var offset = $("#content").offset();
            if($(this).data('id') == id) {
                $(this).css('left', (x+offset.left));
                $(this).css('top',  (y+offset.top));
            }
        });
    }

    $('.navlink-summary  .menuimg').append("<div class='nav-notifications'>4</a>");
    console.log("appended shit");

    // ----------------------------------
    // Checks to see if theme-cookie is set,
    // if not, load default theme.
    // ----------------------------------
    if($.cookie('theme') != null){
        var theme = $.cookie('theme');
        //alert(theme)
        switch(theme){
            case 'balderSmart':
                loadTheme(theme);
                break;
            case 'balder':
                loadTheme(theme);
                break;
            default:
                loadTheme('balder');
                break;
        }
    };


    // $("button").button();
    // Deprecate soon/asap! #TODO
    // $('#tools a').click(function() {
    //     var action = $(this).data('action');
    //     if (action == 'newIdea') {
    //         console.log("trying to show the fancy box");
    //         $.fancybox(
    //             '<div id="newIdeaBox"><h4>New Idea</h4><p>Title: <input type="text" id="createIdeaTitle"></input></p> <p>Description: <input type="text" id="createIdeaDesc"></input></p><p><button id="createIdeaButton">Create Idea</button></p></div>'
    //         );
    //         $('#createIdeaButton').click(function() {
    //             var title=$('#createIdeaTitle').val();
    //             var desc=$('#createIdeaDesc').val();
    //             now.createIdea({title:title,desc:desc});
    //             $.fancybox.close();
    //             refreshContent();
    //         });
    //     }
    // });

    /*$('#newAccount').click(function() {
        //alert("Jews are invading the toilets");
        $.get("newuser",function(html){
            $.fancybox(html,{autoSize:false,width: 362});
        });
        return false;
    });*/
    $("#newAccount").on("click", function(){
        $.get("newuser",function(html){
            //$(".infocontainer").append(html).show("slide");
            $.fancybox(html,{autoSize:true,scrolling:false,
                afterShow : function() {
                    $("input").on('keyup',function () { // -- Muchos validationes!
                        if( !$(this).val() ) {
                            $(this).parent().children("span").css('display', 'block');
                        }
                        else{
                            $(this).parent().children("span").css('display', 'none');
                        }
                        $(this).removeClass("invalidField").removeClass("validField");
                    });
                    $('#FirstName').on('blur', function() {
                        if($(this).val().length >= 2){
                            $(this).removeClass("invalidField").addClass("validField");
                            $(this).val($(this).val().toLowerCase().capitalize());
                            $(this).attr("data-ver","true");
                        }
                        else {
                            $(this).removeClass("validField").addClass("invalidField");
                            $(this).attr("data-ver","false");

                        }
                    });
                    $('#LastName').on('blur', function() {
                        if($(this).val().length >= 2){
                            $(this).removeClass("invalidField").addClass("validField");
                            $(this).val($(this).val().toLowerCase().capitalize());
                            $(this).attr("data-ver","true");
                        }
                        else {
                            $(this).removeClass("validField").addClass("invalidField");
                            $(this).attr("data-ver","false");
                        }
                    });
                    $('#Username').on('blur', function() {
                        $(this).val($(this).val().toLowerCase());
                        var data = {user:{name:$(this).val()}};

                        if($("#Username").val() != ""){
                            now.controlUser(data,function(result){
                                $("#Username").attr("data-ver",result);
                                if(result){
                                    $("#Username").removeClass("invalidField").addClass("validField");
                                    $("#invUsername").css("display","none");
                                    $(this).attr("data-ver","true");

                                }
                                if (!result) {
                                    $("#Username").removeClass("validField").addClass("invalidField");
                                    $("#invUsername").css("display","block");
                                    $(this).attr("data-ver","false");
                                }

                            });
                        }
                        else{
                            $("#invUsername").css("display","none");
                        }
                    });
                    $('#Password1,#Password2').on('blur', function() {
                        var pass1 = $("#Password1").val();
                        var pass2 = $("#Password2").val();
                        if(pass1.length > 0  && pass2.length > 0){
                            if(pass1 != pass2){
                                $("#Password1").removeClass("validField").addClass("invalidField");
                                $("#Password2").removeClass("validField").addClass("invalidField");
                                $("#Password1").attr("data-ver","false");
                                $("#Password2").attr("data-ver","true");
                            }
                            else {
                                $("#Password1").removeClass("invalidField").addClass("validField");
                                $("#Password2").removeClass("invalidField").addClass("validField");
                                $("#Password1").attr("data-ver","true");
                                $("#Password2").attr("data-ver","true");
                            }
                        }
                    });

                    $('#Email').on('blur', function() {
                        if($(this).val().length >= 4 && validateEmail($(this).val())){
                            $(this).removeClass("invalidField").addClass("validField");
                            $(this).attr("data-ver","true");
                        }
                        else {
                            $(this).removeClass("validField").addClass("invalidField");
                            $(this).attr("data-ver","false");
                        }
                    });

                    $("#cancelUser").click(function(){
                        $.fancybox.close();
                    });

                    function checkValidations(){
                        deleteAccountCache();
                        var fname = $('#FirstName').data('ver');
                        var lname = $('#LastName').data('ver');
                        var username = $('#Username').data('ver');
                        var pass1 = $('#Password1').data('ver');
                        var pass2 = $('#Password2').data('ver');
                        var email = $('#Email').data('ver');
                        console.log("Firstname: " + fname);
                        console.log("Lastname: " + lname);
                        console.log("Username: " + username);
                        console.log("Pass1: " + pass1);
                        console.log("Pass2: " + pass2);
                        console.log("Email: " + email);
                        if(fname && lname && username && pass1 && pass2 && email){
                            return true;
                        }
                        else{
                            return false;
                        }
                    }

                    $("#saveUser").on("click", function(){
                        //var b = checkValidations();
                        //console.log("b="+b);
                        if(checkValidations()){
                            var username    =$('#Username').val();
                            var password    =$('#Password1').val();
                            var firstname   =$('#FirstName').val();
                            var lastname    =$('#LastName').val();
                            var email       =$('#Email').val();
                            now.createUser({
                                username:username,
                                password:password,
                                firstname:firstname,
                                lastname:lastname,
                                email:email
                            });
                            $.fancybox.close();
                        }
                        else{
                            alert("Vennligst kontroller at alle felter er korrekt utfylt");
                        }
                    });
                }
            });
        });


        return false;
    });
    
    
    $('#createButton, #creation-menu a').click(function() {
        // now.createEmpty(phase, function(id) {
        //     editIdeaPopup(id);
        // });
        var phase = $(this).data('phase') || 'idea';
        
        $.get('createModal', {phase: phase}, function(html) {
            var modal = $("<div id='createProjectModal' class='modal'></div>").html(html)
            // console.debug(modal)
            modal.modal();
            console.log("things are actually happenng");
            
            $('.modal-footer .next-button').click(function() {
                var title = $('#project-title').val();
                var desc  = $('#project-desc').val();
                now.createProject({title:title, desc:desc, phase:phase, creator:getCreator()}, function(id) {
                    projectView(id);
                });
                console.log("Going next... phase="+phase);
                clearModals();
            });

            $('#createProjectModal .save-button').click(function() {
                var title = $('#project-title').val();
                var desc  = $('#project-desc').val();
                console.log("Saving idea...");
                now.createProject({title:title,desc:desc,creator:getCreator()});
                clearModals();
                refreshContent();
            });

            $('#createProjectModal .delete-button').click(function() {
                var title = $('#project-title').val();
                var desc  = $('#project-desc').val();
                console.log("Deletings idea...");
                now.createProject({title:title,desc:desc,creator:getCreator()});
                var id = $('.modal-header').data('id');
                if(confirm("Trykk OK for å slette denne for godt")) {
                    now.setProjectPhase({id:id,phase:'aborted'});
                    console.log("projectPhase=aborted");
                    clearModals();
                }
                clearModals();
                refreshContent();
            });
        });
    });

    // ----------------------------------
    // When a link from menu is clicked,
    // execute loadContent function
    // ----------------------------------
    $('nav li a').click(function() {
        // [deprecated] initially introduced to prevent spamming;
        // however, refershing turns out to be useful
        // if ($(this).hasClass("selected")) return false;
        var toLoad = '/'+$(this).data('value');
        var phase = $(this).data('phase') || 'idea';
        $('nav li a.selected').removeClass('selected');
        $(this).addClass("selected");
    	$('#content').fadeOut(50).load(toLoad, function() {
            if (toLoad == '/tasks') {
                loadQuartal(-1,'task',-1); // -1 = get current (from server)
                changeQuartalState('task');
                $("#excelGroup").flexigrid({
                    url: '/getProjectSpreadSheet',
                    dataType: 'json',
                    colModel : [
                        {display: 'Rad', name : '_id', width : 40, sortable : false, align: 'center'},
                        {display: 'dbID', name : '_id', width : 40, sortable : false, align: 'center',hide:true},
                        {display: 'Tittel', name : 'title', width : 180, sortable : true, align: 'left'},
                        {display: 'Beskrivelse', name : 'desc', width : 300, sortable : true, align: 'left'},
                        {display: 'Leder', name : 'leader', width : 150, sortable : true, align: 'center'},
                        {display: 'Øk.ramme', name : 'ecoframe', width : 100, sortable : true, align: 'center'},
                        {display: 'Oppstart', name : 'dateCreated', width : 60, sortable : true, align: 'left'},
                        {display: 'Sluttdato', name : 'dateEnd', width : 60, sortable : true, align: 'left'}
                    ],
                    sortname: "dateCreated",
                    sortorder: "asc",
                    usepager: false,
                    title: null,
                    useRp: true,
                    height: 350,
                    state: "task",
                    rp: 15,
                    showTableToggleBtn: true,
                    singleSelect:true
            });
            $('.flexigrid').on('click', 'tr[id*="row"]', function(){
                var id = $(this).attr('id').substr(3);
                projectView(id);
            });

                $("#excelView").click(function(){
                    showExcelView($(this));
                });
                $("#quartalView").click(function(){
                    showQuartalView($(this));
                });
                $("#ganttView").click(function(){
                    showGanttView($(this));
                });
                /*$("#ganttView2").click(function(){
                    showGanttView2($(this));
                }); */
                $(".quartalSelection a").click(function(){
                    showQuartal($(this));
                });
                yearDropDown();


            } else if(toLoad == '/proposals'){
                loadQuartal(-1,'proposal',-1);
                changeQuartalState('proposal')
                $("#excelGroup").flexigrid({
                    url: '/getProposalSpreadSheet',
                    dataType: 'json',
                    colModel : [
                        {display: 'Rad', name : '_id', width : 40, sortable : false, align: 'center'},
                        {display: 'dbID', name : '_id', width : 40, sortable : false, align: 'center',hide:true},
                        {display: 'Tittel', name : 'title', width : 180, sortable : true, align: 'left'},
                        {display: 'Beskrivelse', name : 'desc', width : 200, sortable : true, align: 'left'},
                        {display: 'Leder', name : 'leader', width : 150, sortable : true, align: 'center'},
                        {display: 'Øk.ramme', name : 'ecoframe', width : 100, sortable : true, align: 'center'},
                        {display: 'Datert', name : 'dateCreated', width : 60, sortable : true, align: 'left'},
                        {display: 'Oppstart', name : 'dateStart', width : 60, sortable : true, align: 'left'},
                        {display: 'Sluttdato', name : 'dateEnd', width : 60, sortable : true, align: 'left'}
                    ],
                    sortname: "dateCreated",
                    sortorder: "asc",
                    usepager: false,
                    title: null,
                    useRp: true,
                    height: 350,
                    state: "proposal",
                    rp: 15,
                    showTableToggleBtn: true,
                    singleSelect:true

                });
                $('.flexigrid').on('click', 'tr[id*="row"]', function(){
                    var id = $(this).attr('id').substr(3);
                    projectView(id);
                 });
                //$(".flexigrid").css("display","block");

                $("#excelView").click(function(){
                    showExcelView($(this));
                });
                $("#quartalView").click(function(){
                    showQuartalView($(this));
                });
                $(".quartalSelection a").click(function(){
                    showQuartal($(this));
                });
                yearDropDown();

            } else if(toLoad=='/admin'){
                $( ".selectUsers" ).selectable({
                    filter: "li",
                    selected: function(event, ui) {
                        //alert("No cookie for you good sir");
                        $("#acceptUser").css("display","block");
                        $("#denyUser").css("display","block");
                    },
                    unselected: function(event, ui) {
                        $("#acceptUser").css("display","none");
                        $("#denyUser").css("display","none");
                    }
                });
                $("#acceptUser").click(function(){
                    $(".ui-selected").each(function() {
                        //var index = $(".selectUsers li").index(this);
                        var id = $(this).data("id");
                        var email = $(this).data("email");
                        $.post('/updateUser',{_id:id,level:1,email:email},function(result){
                            if (result) console.log("[/updateUser] done..." + result);
                        });
                        $(this).remove();
                    });
                });
                $("#denyUser").click(function(){
                    $(".ui-selected").each(function() {
                        //var index = $(".selectUsers li").index(this);
                        var id = $(this).data("id");
                        $.post('/updateUser',{_id:id,level:-1},function(result){
                            if (result) console.log("[/updateUser] done..." + result);
                        });
                        $(this).remove();
                    });
                });

            } else if (toLoad == '/ideas') {
                console.info("making them draggable now");

                $('.idea').tooltip({placement:'bottom'});
                $('.idea').draggable({
                    stop: function(event, ui) {
                        var offset = $("#content").offset();
                        // $.notification "(#{ui.position.top}, #{ui.position.left})",
                        now.saveIdeaPosition($(this).data("id"), (ui.position.left-offset.left),
                            (ui.position.top-offset.top))
                    },
                    revert: "valid",
                    scroll: true,
                    containment: "#content"
                });
                // $(".idea").click(function(){
                //     var ideaId = $(this).data('id');
                //     console.log("ideaId="+ideaId);
                //     now.editIdeaForm(ideaId, function(html) {
                //         $.fancybox(html);
                //     });
                // });
                $(".idea").each(function() {
                    var offset = $("#content").offset();
                    //console.log("Offset: "+offset.left);
                    var x = ($(this).data("x")+offset.left);
                    var y = ($(this).data("y")+offset.top);
                    var color = $(this).data("color");
                    // remember position (x,y)
                    if(x != null && y != null) {
                        $(this).css('left', x);
                        $(this).css('top',  y);
                    }
                });
            } else if(toLoad == '/evaluations'){
                $("#evalutationlist").flexigrid({
                    url: '/getEvaluation',
                    dataType: 'json',
                    colModel : [
                        {display: 'Rad', name : 'id', width : 40, sortable : false, align: 'center'},
                        {display: 'dbID', name : '_id', width : 40, sortable : false, align: 'center',hide:true},
                        {display: 'Tittel', name : 'title', width : 180, sortable : true, align: 'left'},
                        {display: 'Beskrivelse', name : 'desc', width : 300, sortable : true, align: 'left'},
                        {display: 'Evaluert', name : 'evalueted', width : 60, sortable : true, align: 'center'},
                        {display: 'Leder', name : 'leader', width : 120, sortable : true, align: 'center'},
                        {display: 'Øk.ramme', name : 'ecoframe', width : 100, sortable : true, align: 'center'},
                        {display: 'Start', name : 'dateStart', width : 60, sortable : true, align: 'left'},
                        {display: 'Avsluttet', name : 'dateEnd', width : 60, sortable : true, align: 'left'}
                    ],
                    sortname: "dateEnd",
                    sortorder: "asc",
                    usepager: false,
                    title: null,
                    useRp: true,
                    height: 350,
                    state: "completed",
                    singleSelect:true,
                    rp: 15,
                    showTableToggleBtn: true,
                    buttons : [
                        {name: 'Sett til evaluert', bclass: 'true', onpress : doCommand},
                        {name: 'Fjern som evaluert', bclass: 'false', onpress : doCommand},
                        {separator: true}
                    ]

                });
                $('.flexigrid').on('dblclick', 'tr[id*="row"]', function(){
                    var id = $(this).attr('id').substr(3);
                    projectView(id);
                });
                $(".flexigrid").css("display","block");
                /*$('.flexigrid').on('mouseenter', 'tr[id*="row"]', function(){
                    console.log('mouseenter rowId: ' + $(this).attr('id').substr(3));
                }); */
                function doCommand(com, grid) {
                    if (com == 'Sett til evaluert') {
                        $('.trSelected', grid).each(function() {
                            var id = $(this).attr('id');
                            id = id.substring(id.lastIndexOf('row')+3);
                            $.post('/setEvaluated',{_id:id,evaluated:true},function(result){
                                if(result == true){
                                    console.log("/setEvaluated completed..");
                                    $('.navlink-evaluations').click();
                                }
                            });
                        });
                    } else if (com == 'Fjern som evaluert') {
                        $('.trSelected', grid).each(function() {
                            var id = $(this).attr('id');
                            id = id.substring(id.lastIndexOf('row')+3);
                            $.post('/setEvaluated',{_id:id,evaluated:false},function(result){
                                if(result == true){
                                    console.log("/setEvaluated completed..");
                                    $('.navlink-evaluations').click();
                                }
                            });
                        });
                    }
                }
            }
            else if(toLoad =='/settings'){
                $("option").attr('selected','');
                $("option[value="+$.cookie('theme')+"]").attr('selected','selected');
                $("#changePass").click(function() {
                    $("input").on('keyup',function () {
                        validateKeyUp($(this));
                    });
                    $(".passwordContainer").slideToggle("fast");
                    $('#Password0,#Password1,#Password2').on('blur', function() {

                        var pass0 = $("#Password1").val();
                        var pass1 = $("#Password1").val();
                        var pass2 = $("#Password2").val();
                        if(pass1.length > 0  && pass2.length > 0){
                            if(pass1 != pass2){
                                invalidateField("#Password1");
                                invalidateField("#Password2");
                                $("#savePass").data("disabled", "true");
                            } else {
                                validateField("#Password1");
                                validateField("#Password2");
                                $("#savePass").data("disabled", "false");
                            }
                        }
                        else $("#savePass").data("disabled", "true");
                    });
                    $("#savePass").click(function() {
                        if ($(this).data("disabled") == "false"){
                            var pass0   = $("#Password0").val();
                            var pass    = $("#Password1").val();
                            $.post('/checkUserPass',{password:pass0},function(result){
                                if(result == "true"){
                                    $.post('/updateUser',{_id:"none",password:pass},function(result){
                                        if (result) console.log("[/updateUser] done..." + result);
                                        validateField("#Password0");
                                        $(".passwordContainer").slideToggle("fast");
                                        $("#changePass").removeClass("btn-danger").addClass("btn-success");
                                    });
                                } else {
                                    //alert("There is poop in the chimney");
                                    invalidateField("#Password0");
                                }
                            });

                        }
                    });
                });
                $("#changeMail").click(function() {
                    $("input").on('keyup',function () {
                        validateKeyUp($(this));
                    });
                    $(".mailContainer").slideToggle("fast");
                    $('#Email1,#Email2').on('blur', function() {
                        var email1 = $("#Email1").val();
                        console.log(email1);
                        var email2 = $("#Email2").val();
                        console.log(email2);
                        if(email1.length > 0  && email2.length > 0 && validateEmail(email1) && validateEmail(email2)){
                            if(email1 != email2){
                                invalidateField("#Email1");
                                invalidateField("#Email2");
                                $("#saveMail").data("disabled", "true");
                            } else {
                                validateField("#Email1");
                                validateField("#Email2");
                                $("#saveMail").data("disabled", "false");
                            }
                        } else {
                            (validateEmail(email1) ? validateField("#Email1"): invalidateField("#Email1"));
                            (validateEmail(email2) ? validateField("#Email2"): invalidateField("#Email2"));
                            $("#saveMail").data("disabled", "true");

                        }
                    });
                    $("#saveMail").click(function() {
                        if ($(this).data("disabled") == "false"){
                            var passMail   = $("#PasswordMail").val();
                            var mail    = $("#Email1").val();
                            $.post('/checkUserPass',{password:passMail},function(result){
                                if(result == "true"){
                                    $.post('/updateUser',{_id:"none",newmail:mail},function(result){
                                        if (result) console.log("[/updateUser] done..." + result);
                                        validateField("#PasswordMail");
                                        $(".mailContainer").slideToggle("fast");
                                        $("#changeMail").removeClass("btn-danger").addClass("btn-success");
                                        $(".userText").text(mail);
                                    });
                                } else {
                                    invalidateField("#PasswordMail");
                                }
                            });

                        }
                    });
                });
            } else {
                //Do nothing
            }

        }).fadeIn(300)
        return false; // !!
    });

    // ----------------------------------
    // On quartal click events
    // ----------------------------------
    $('ul#quarters li a').click(function() {
        // too annoying; removed
        // if ($(this).hasClass("selected")) return false;

        $('ul#quarters li a.selected').removeClass('selected');
        $(this).addClass("selected");

        var quarter = $(this).data('quarter');
        var state   = $('#tools').data('state');
        var year    = $('.yearSelector').data('year');
        console.log("trying to load state: "+state);
        loadQuartal(quarter, state,year);
        //return false;
    });

    // ----------------------------------
    // Loads quartal from parameter [1-4]
    // ----------------------------------
    function loadQuartal(quarter,phase,year){
        flush();
        if(quarter == -1) {
            var d = new Date(Date.now());
            quarter = Math.floor((d.getMonth()-1)/3) + 1;
            year = new Date().getFullYear();//Current year
            console.log("Current quarter="+quarter+".");
        }
        var quarterMonths = quarterArray[quarter-1];
        for(var monthIndex in quarterMonths) {
            var month_label = quarterMonths[monthIndex];
            loadMonth(monthIndex,month_label,phase,year);
        }
        $('.quartal'+quarter).css("display","block");
        $('.quartalSelection a').removeClass('btn-danger');
        $('.quartalSelection a').addClass('');
        $('#quartal'+quarter).removeClass('');
        $('#quartal'+quarter).addClass('btn-danger');
        $('.quartalSelection').attr('data-selectedquartal',quarter);
    }

    // ----------------------------------
    // Squirtle
    // ----------------------------------
    var loadMonth = function(month_index, month_label,phase,year) {
        var sort;
        console.log("Phase"+phase);
        switch(phase){
            case "task":
                sort = {sortby:"dateEnd",asc:1};
                break;
            case "proposal":
                sort = {sortby:"dateCreated",asc:1};
                break;
            default:
                sort = {sortby:"dateEnd",asc:1};
                break;
        }
        var monthId= parseInt(month_index)+1;
        var year = parseInt(year);
        var container = "#period"+monthId;
        $('#period'+monthId+" h3").text(month_label);

        now.getProjects({
            // month: 3,
            month: month_index,
            phase: phase,
            year: year,
            container: container,
            sort:sort
        });
    };

    var flush = function() {
        $('#content .period .task').remove();
        for (var a=1;a<=4;a++){
            $('.quartal'+a).css("display","none");
        }
    };

    // ----------------------------------
    // Squirtle
    // ----------------------------------
    $('#notification-counter').click(function() {
        $('#notifications-menu').toggle();
    });


    // ----------------------------------
    // Changes theme based on current
    // selection value from id='themechanger',
    // ----------------------------------
    /*$("#content").on("click","#theme-select a", function(){
    //$('#theme-select a').click(function(){
        var selectedtheme = $(this).data("theme");
        $('#theme-select').removeClass('selected');
        $(this).addClass('selected');
        loadTheme(selectedtheme);
        $.post('/saveCookie', {themechanger: selectedtheme});
        return false;
    });*/

    // ----------------------------------
    // Changes theme based on current
    // selection value from id='themechanger',
    // and changes logo in the same manner
    // ----------------------------------
    //$('#themechanger').change(function(){
    $("#content").on("change","#themechanger", function(){
        var selectedtheme = $('#themechanger').val();
        loadTheme(selectedtheme);
        $.post('/saveCookie', {themechanger:selectedtheme});
        return false;
    });

    // ----------------------------------
    // Loads theme-name received from parameter
    // ----------------------------------
    function loadTheme(theme){
        $('link#theme').attr('href','/stylesheets/themes/'+theme+"/"+theme+".css");
        $('img#mainlogo').attr('src','/stylesheets/themes/'+theme+'/logo_'+theme+'.png');
        setThemeBar(theme);
    }

    function setThemeBar(theme){
        switch(theme){
            case 'balder':
                $(".navbar").removeClass().addClass('navbar navbar-fixed-top');
                $(".btn-group").removeClass('dropup');
                $("#padder").css("display","block");
                break;
            case 'balderSmart':
                $(".navbar").removeClass().addClass('navbar navbar-fixed-bottom');
                $(".btn-group").addClass('dropup');
                $("#padder").css("display","none");
                break;
            default:
                $(".navbar").removeClass().addClass('navbar navbar-fixed-bottom');
                $(".btn-group").removeClass('dropup');
                $("#padder").css("display","block");
                break;
        }
    }

    // ----------------------------------
    // Squirtle
    // ----------------------------------
    now.refreshCss = function() {
        $(".css").each(function() {
            href=$(this).attr("href");
            console.log("reloading "+href);
            $(this).attr("href","");
            setTimeout(function() {$(this).attr("href",href);}, 150);
        });
    };


    // ----------------------------------
    // Squirtle
    // ----------------------------------


    // END Midgard functions
    // -------------------------------------------------------------------



    // -------------------------------------------------------------------
    // now() functions
    // -------------------------------------------------------------------
    now.messageAll = function (opts) {
        now.broadcastNotification(opts);
    };

    now.gritt = function(opts) {
        $.gritter.add({
            title: opts.title,
            text: opts.text,
            position: "top-right",
            image: opts.image || './images/sintef_logo.png',
            target: opts.target || '#content',
            sticky: true
        });
    };

    now.notify = function(text) {
        $.notification(text, {
            position: "bottom-right"
        })
    };

    now.ready(function() {
        // now.hello("world", function(phrase) {alert(phrase);});
        now.fetchUserList(function(userList) {
            USERS = userList; // User list is a global ´CONSTANT´ used for bla.a. autocomplete
        });
    });

    now.receiveProjects = function(data, container,pId){
        //console.info("received project with id="+data._id.toString());
        var risk = data.risk || 'low';
        $(container).append(
            "<div data-id='"+ pId +"' class='task'>"+
                "<div class='taskheader btn-inverse'>" +
                    "<span class='risk "+risk+"-risk'></span>"+
                    "<h4>"+ data.title+"</h4>"+

                "</div>"+
                "<p>"+ data.desc +"</p>"+
            "</div>");
    }

    // END now() functions
    // -------------------------------------------------------------------

    // -------------------------------------------------------------------
    // jQuery plugin functions
    // -------------------------------------------------------------------
    //
    //
    var projectView = function(projId) {
        console.log("fetching projectView id="+projId);
        var userNames = _.map(USERS, function(u) {return u.name});
        $.get('projectView', {_id:projId}, function(html) {
            console.log("viewing projectView id="+projId)
            var modal = $("<div id='projectView' class='modal bigModal'></div>").html(html)
            // console.debug(modal)
            modal.modal();
            $('.change-risk button').tooltip();
            $('.change-risk button').click(function() {
                var wasSelected = $(this).is('.active')
                if (wasSelected) {
                    console.log("Was already active/selected, so, derp it!");
                    return;
                }
                var t=$(this);
                var risk = t.data('risk');
                $('#hidden-risk-field').val(risk);
                var reasonArea = $('.risk-reason');
                reasonArea.removeAttr('disabled');
                // reasonArea.val('');
                reasonArea.focus();
                // reasonArea.addClass('alert-info'); // too much maeby?
            });
            $('.delete-button').click(function() {
                // $('.modal-body,.modal-header,.modal-footer').addClass('alert-danger');
                var id = $('.modal-header').data('id');
                if(confirm("Trykk OK for å slette dette prosjektet for godt")) {
                    now.setProjectPhase({id:id, phase:'aborted'});
                    console.log("projectPhase=aborted");
                    clearModals();
                }
            });
            
            $('.cancel-button').click(function() {clearModals()});
            $('.add-resource-button').click(function() {
                console.log("trying to add the input field")
                var b = $(this).parent('.span8');
                console.debug(b);
                var found  = false;
                $('.resource-input').each(function() {
                    found = true;
                    $(this).focus()
                });
                if (found) return;
                $('<input type="text" class="resource-input alert alert-info"></input>').insertBefore($(this));
                $('.resource-input').typeahead({source:userNames});
                $('.resource-input').focus();
                var acceptInput = function() {
                    var val = $('.resource-input').val(); // val = 'Sobah Pettersen' e.x.
                    if (!val){$('.resource-input').remove();return;} // hotfix
                    now.addResourceToProject(projId, val);
                    $('.resource-input').remove();
                    b.append("<div class='alert alert-info resource pull-left' style='padding:2px;margin-left:3px;'>"+val+"</div>");
                };
                $('.resource-input').live('keypress', function(e) {
                    if (e.keyCode == 13) {
                        acceptInput()
                        e.preventDefault()
                    }
                });
                $('.resource-input').on('blur', function() {_.delay(acceptInput, 300)});
            });

            $('.remove-resource-button').click(function() {
                var e = $(this).parent('.resource')
                console.debug(e)
                var rsc_id = e.data('id');
                var name = e.data('name');
                console.warn("Should now remove resource {id:"+rsc_id+", name:"+name+"}")
                e.remove()
                now.removeResourceFromProject({id:projId, rsc_id:rsc_id})
            });

            _.delay(function() {
                console.log("door hinge");
                $('input[data-type=date]').each(function() {
                    console.log("foobar");
                    var old = $(this).data('old');
                    console.log("trying to set to "+old);
                    console.debug(this);
                    $(this).val(old);
                });
                console.log("door hinge done");
            }, 500);

            //////////////////////////////////////////////////// LOAN
            /*
            var save = function(nextphase) {
                var title = $('#project-title').val();
                var desc  = $('#project-desc').val();
                console.log("saving... title= "+title+" ; desc="+desc);
                clearModals();
                now.saveProperties(projId, {title:title, desc:desc, phase:nextphase || 'proposal'});
            };
            
            $('.next-button, .next-menu a').click(function() {
                var phase = $(this).data('phase') || 'proposal';
                save(phase);
                projectView(projId);
                console.log("Going next...");
            });
            */
            //////////////////////////////////////////////////////
            var save = function(id, phase) {
                console.log("Saving...")
                var toSave = {};
                if (phase) toSave.phase=phase;
                $('.modal-body input, .modal-body textarea').each(function() {
                    var t=$(this); // ?!
                    var val = t.val();
                    var prop = t.data('property');
                    console.log("id: "+id+", attr: "+prop+", value: "+val);
                    if (prop) {
                        toSave[prop] = val;
                        // now.setProjectAttribute({id:id, attr:prop, value:val});
                    }
                });

                now.saveProperties(id, toSave);
            };
            
            $('.next-button').click(function() {
                save(projId, $(this).data('phase') || 'task');
                clearModals();
                if($(this).data('phase')!='completed') projectView(projId);
            });
            
            $('.save-button').click(function() {
                save(projId);
                clearModals();
            });

            $('.modal-footer .btn').tooltip();
            $('input[data-type=user]').typeahead({source:userNames});
            $('input[data-type=date]').datepicker();
            $('input[data-type=date]').datepicker("option", "dateFormat", 'dd.mm.yy');
        });
    }

    var ideaView = function(projId) {
        $.get('ideaView', {_id:projId}, function(html) {
            console.log("viewing id="+projId);
            var modal = $("<div id='ideaView' class='modal'></div>").html(html)
            // console.debug(modal)
            modal.modal();
            $('.delete-button').click(function() {
                var id = $('.modal-header').data('id');
                if(confirm("Trykk OK for å slette denne idéen for godt?")) {
                    now.setProjectPhase({id: projId, phase:'aborted'});
                    console.log("projectPhase=aborted");
                    clearModals();
                }
            });
            $('.modal-footer .btn').tooltip();

            var save = function(nextphase) {
                var title = $('#project-title').val();
                var desc  = $('#project-desc').val();
                console.log("saving... title= "+title+" ; desc="+desc);
                clearModals();
                now.saveProperties(projId, {title:title, desc:desc, phase:nextphase || 'idea'});
            };

            console.debug(projectView)

            $('.next-button').click(function() {
                var phase = $(this).data('phase') || 'proposal';
                save(phase);
                projectView(projId);
                console.log("Going next...");
            });


            $('.save-button').click(function() {
                save();
            });

            $('.cancel-button').click(function() {clearModals()});
        });
    };

    $("#content").on("click",".task, .proposal", function(){
        var projId = $(this).attr("data-id");
        projectView(projId);
    });

    $("#content").on("click",".idea", function(){
        var projId = $(this).attr("data-id");
        ideaView(projId);
    });

    function showExcelView(item){
        $(".quartalGroup").css("display","none");
        $(".flexigrid").css("display","block");
        $(".quartalSelection").css("display","none"); // automate soon. nix todo
        $(".yearSelector").css("display","none");
        $("#gantt").css("display","none");
    }
    function showQuartalView(item){
        $(".quartalGroup").css("display","block");
        $(".flexigrid").css("display","none");
        $(".quartalSelection").css("display","inline-block"); // automate soon. nix todo+
        $(".yearSelector").css("display","inline-block");
        $("#gantt").css("display","none");
    }
    function showQuartal(item){
        $(".quartalSelection a").removeClass("btn-danger").addClass("");
        $(item).removeClass("").addClass("btn-danger");
        var quarter = $(item).data('quarter');
        var state   = $('.quartalSelection').data('state');
        var year    = $('.yearSelector').data('year');
        loadQuartal(quarter, state, year);
    }

    function showGanttView(item){
        $(".quartalGroup").css("display","none");
        $(".flexigrid").css("display","none");
        $(".yearSelector").css("display","none");
        $("#gantt").css("display","block");
        $(".quartalSelection").css("display","none");
        $("#gantt").empty();
        var gantt = new GanttChart();
        insertGanttData();
     }


    function insertGanttData(){
        var gantt = new GanttChart();
        gantt.setImagePath("gantt2/imgs/");
        gantt.setEditable(false);
        $.post("/getGantt",function(res){
            for(var n = 0;n<res.length;n++){
                var dateStart, dateEnd;
                //console.log(res[n].dateStart);
                //console.log(res[n].title);
                if(res[n].dateStart != null && res[n].dateStart != "undefined" && res[n].dateStart>0
                    && res[n].dateEnd != null && res[n].dateEnd != "undefined" && res[n].dateEnd>0){
                    dateStart =res[n].dateStart*1000;//(new Date(2012, 4, 4));//new Date(res[n].dateStart*1000);
                    dateEnd =  res[n].dateEnd*1000;//(new Date(2012, 4, 8));//new Date(res[n].dateEnd*1000);
                }
                else{
                    dateStart = new Date(2012,4,4).getTime();
                    dateEnd = new Date(2012,4,8).getTime();
                }

                var lengthInHours = getTimeDifference(dateStart,dateEnd);
                var newProject = new GanttProjectInfo(res[n]._id||0, res[n].title,dateStart);
                var newTask = new GanttTaskInfo(res[n]._id||0, res[n].desc,dateStart, lengthInHours*8, timeDifferenceAsPercent(dateStart,dateEnd), "");
                newProject.addTask(newTask);
                gantt.addProject(newProject);
                //console.log("added project GANTT: " + res[n].title + " time: " +lengthInHours);
            }
            gantt.create("gantt");
        });

        //var project_1 = new GanttProjectInfo(1, "SINTEF Prosjekt 1", new Date(2012, 4, 4));
        //var task_1 = new GanttTaskInfo(1, "Dette er arbeid!", new Date(2012, 4, 4), 208, 50, "");
        //var project_2 = new GanttProjectInfo(1, "SINTEF Prosjekt 2", new Date(2012, 4, 16));
        //var task_2 = new GanttTaskInfo(1, "Dette er arbeid!", new Date(2012, 16, 4), 40, 100, "");
        //project_1.addTask(task_1);
        //project_2.addTask(task_2);
        //gantt.addProject(project_1);
        //gantt.addProject(project_2);
        //gantt.create("gantt");
    }

    function timeDifferenceAsPercent(_1,_2){
        var dateNow = parseInt((new Date().getTime()));
        if (dateNow <= _1) return 0;
        else if (dateNow >= _2) return 100;
        else{
            return ((((_1+_2)-dateNow)*100)/(_1+_2));
        }
    }

    function yearDropDown(){
        $('#year').dropdown();
        var i = new Date().getFullYear();

        for (var c = 2000; c <= 2030; c++)
        {
            if (c == i){
                $('#yearValues').append("<li><a class='alert-success' data-selected='true' data-value='"+c+"'>"+c+"</a></li>");
            }
            else {$('#yearValues').append("<li><a data-selected='false' data-value='"+c+"'>"+c+"</a></li>");}

        }
        $("#year").click(function(){
            var posCurrentYear = $('#yearValues [data-selected=true]');//.position.top;
            $("#yearValues").scrollTop(posCurrentYear.position().top-23);
        });

        $("#yearValues a").on("click",function(){
            deleteQuartalCache();
            $("#yearValues a").removeClass("alert-success");
            $('[data-selected]').attr("data-selected","false");
            $(this).addClass("alert-success");
            $(this).attr("data-selected","true");
            var selectedyear = $('[data-selected=true]').attr("data-value");
            $('.yearSelector').attr("data-year",selectedyear);
            $('#year').html(selectedyear + ' <span class="caret"></span>');
            var quarter = $('.quartalSelection').data('selectedquartal');
            //console.log("Quarter:"+quarter);
            var state   = $('.quartalSelection').data('state');
            //console.log("State: "+state);
            var year    = $('.yearSelector').data('year');
            //console.log("Year: "+year);
            loadQuartal(quarter, state,year);
        });
    }

    String.prototype.capitalize = function() {
        return this.charAt(0).toUpperCase() + this.slice(1);
    }

    function changeQuartalState(state){
        console.log("changeQuartalState(): #tools(data-state="+state);
       $("#tools").data("state", state);
       $(".quartalSelection").data("state", state);
    }

    function invalidateField(field){
        $(field).removeClass("validField").addClass("invalidField");
        $(field).attr("data-ver","false");
    }
    function validateField(field){
        $(field).removeClass("invalidField").addClass("validField");
        $(field).attr("data-ver","true");
    }

    function validateKeyUp(field){
        if( !$(field).val() ) {
            $(field).parent().children("span").css('display', 'block');
        }
        else{
            $(field).parent().children("span").css('display', 'none');
        }
        $(field).removeClass("invalidField").removeClass("validField");
    }

    function validateEmail(email){
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        var valid = reg.test(email);
        if(valid) {
            return true;
        } else {
            return false;
        }
    }

    function deleteQuartalCache(){
        $(".yearSelector").removeData("year");
        $(".quartalSelection").removeData("selectedquartal");
        //$(".quartalSelection").removeData("state");
    }

    function deleteAccountCache(){
        $('#FirstName').removeData('ver');
        $('#LastName').removeData('ver');
        $('#Username').removeData('ver');
        $('#Password1').removeData('ver');
        $('#Password2').removeData('ver');
        $('#Email').removeData('ver');
    }

    function clearModals() {
        _.delay(function() {
            $('.modal').modal('hide');
            $('.modal').remove();
            $('.tooltip').remove(); //bug =(
            console.log("clear'd them modals");
            refreshContent();
            console.log("refresh'd them #contents");
        }, 300);
    }
        
    function getTimeDifference(_1,_2){
        var workingday = 1000*60*60*24;
        console.log("DateStart:"+_1+" DateEnd: "+_2 + "Result:" + ((_2-_1)/workingday));
        return ((_2-_1)/workingday);
    }
    // -------------------------------------------------------------------
    // droppable functions
    // -------------------------------------------------------------------
    // $("[data-value=proposals], [data-value=tasks], [data-value=evaluation]").droppable({
    //     activeClass: "ui-state-hover",
    //     hoverClass: "ui-state-active",
    //     accept: ".idea,.task,.proposal",
    //     drop: function( event, ui ) {
    //         //do stuff
    //         console.debug(event);
    //         console.debug(ui);
            
    //         // $(event.toElement).is('proposals'); elns nix fix todo magnus foobar
    //         // event.target
    //     }
    // });


    $("#content").live("mouseover",function(){
        $('.task').draggable({
            revert: true
        });
    });

    _.delay(function() {
        $('.navlink-summary').click();
    }, 5);

    // var antallIs [3,3];
    function antallToIs(is){
        var ikkeToIs = 0;
        var toIs = 0;
        for(var a in antallIs){
            if ((is%2)>0){
                ikkeToIs++;
            }
            else{
                toIs++;
            }
        }
        if (ikkeToIs%2 == 0){
            toIs += (ikkeToIs/2);
        }
        else{
            toIs+=((ikkeToIs-1)/2)
        }
        return toIs;

    }

});// MidgardEND